﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.ComponentModel;


namespace inventory.Controls
{
    public class gridInventoryDetail : common.controls.baseDataGridView 
    {
        public enum ColumnNames
        {
            isChecked, itemCode, subCode, techcode,
            itemName, unit, qty, whQty, convertUnit,
            convertQty, convertMetric, notes, houseCode, contractNo, deliveryLot, actionBtn
        };

        public gridInventoryDetail()
        {
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.AutoArrange();
            this.myOnFind += new OnCellEvent(FindData);
            this.myOnCellValueChanged += new OnCellEvent(ValueChanged);
        }

        public void UpdateItemList(string itemCode)
        {
            if (itemCode == null)
            {
                for (int idx = 0; idx < this.Rows.Count; idx++)
                {
                    if (this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value == null) continue;
                    DataAccess.DataCache.FindITEM(this.Rows[idx].Cells[ColumnNames.itemCode.ToString()].Value.ToString());
                }
            }
            else DataAccess.DataCache.FindITEM(itemCode);
        }

        public override void Init(BindingSource dataSource)
        {
            base.Init(dataSource);
            
            data.applicationDS.InventoryDetailDataTable detailTbl = (data.applicationDS.InventoryDetailDataTable)dataSource.DataSource;
            
            DataGridViewCellStyle qtyCellType = new DataGridViewCellStyle();
            DataGridViewCellStyle whQtyCellType = new DataGridViewCellStyle();

            string precisionStr = common.SysLibs.GetPrecisionFromMask(CommonTypes.Settings.sysMaskQty).ToString(); 
            qtyCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            qtyCellType.Format = "N" + precisionStr; qtyCellType.NullValue = null;

            whQtyCellType.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleRight;
            whQtyCellType.Format = "N" + precisionStr; 
            qtyCellType.NullValue = null;
            whQtyCellType.BackColor = CommonTypes.Settings.sysColorDisableBG;
            whQtyCellType.ForeColor = CommonTypes.Settings.sysColorDisableFG; 

            // 
            // checkOut
            // 
            DataGridViewCheckBoxColumn checkOut = new DataGridViewCheckBoxColumn();
            checkOut.DataPropertyName = detailTbl.isCheckedColumn.ColumnName;
            checkOut.HeaderText = "";
            checkOut.Name = ColumnNames.isChecked.ToString();
            checkOut.Width = 20;
            checkOut.Visible = false;
            // 
            // itemCode
            // 
            common.controls.DataGridViewTextBoxColumnExt itemCode = new common.controls.DataGridViewTextBoxColumnExt();
            itemCode.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemCode.HeaderText = "Mã.hàng";
            itemCode.Name = ColumnNames.itemCode.ToString();
            itemCode.Width = 90;
            itemCode.Uppercase = true;

            // 
            // subCode
            // 
            DataAccess.DataCache.LoadITEMSUBCODE();
            BindingSource itemSubCodeSource = new BindingSource();
            itemSubCodeSource.DataSource = DataAccess.DataCache.myMasterDS.itemSubCode;

            DataGridViewComboBoxColumn subCode = new DataGridViewComboBoxColumn();
            subCode.DataPropertyName = detailTbl.subCodeColumn.ColumnName;
            subCode.HeaderText = " +";
            subCode.Name = ColumnNames.subCode.ToString();
            subCode.Width = 50;
            subCode.DataSource = itemSubCodeSource;
            subCode.DisplayMember = DataAccess.DataCache.myMasterDS.itemSubCode.codeColumn.ColumnName;
            subCode.ValueMember = DataAccess.DataCache.myMasterDS.itemSubCode.codeColumn.ColumnName;
            subCode.DefaultCellStyle.NullValue = " "; //Must be one space at least

            // 
            // techCode
            // 
            BindingSource itemSource = new BindingSource();
            itemSource.DataSource = DataAccess.DataCache.myMasterDS.Item;
            DataGridViewComboBoxColumn techCode = new DataGridViewComboBoxColumn();
            techCode.DataSource = itemSource;
            techCode.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            techCode.DisplayMember = DataAccess.DataCache.myMasterDS.Item.techCodeColumn.ColumnName;
            techCode.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            techCode.HeaderText = "Mã.kỹ.thuật";
            techCode.Name = ColumnNames.techcode.ToString();
            techCode.ReadOnly = true;
            techCode.Width = 100;
            techCode.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            techCode.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            techCode.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing; 

            // 
            // itemName
            // 
            DataGridViewComboBoxColumn itemName = new DataGridViewComboBoxColumn();
            itemName.DataSource = itemSource;
            itemName.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            itemName.DisplayMember = DataAccess.DataCache.myMasterDS.Item.nameColumn.ColumnName;
            itemName.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            itemName.HeaderText = "Diễn giải";
            itemName.Name = ColumnNames.itemName.ToString();
            itemName.ReadOnly = true;
            
            itemName.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            itemName.Width = 170;
            itemName.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            itemName.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            
            // 
            // unit
            // 
            DataGridViewComboBoxColumn unit = new DataGridViewComboBoxColumn();
            unit.DataSource = itemSource;
            unit.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            unit.DisplayMember = DataAccess.DataCache.myMasterDS.Item.unitColumn.ColumnName;
            unit.ValueMember = DataAccess.DataCache.myMasterDS.Item.itemCodeColumn.ColumnName;
            unit.HeaderText = "ĐVT";
            unit.Name = ColumnNames.unit.ToString();
            unit.ReadOnly = true;
            unit.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            unit.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            unit.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG; 
            unit.Width = 60;
            // 
            // Qty
            // 
            DataGridViewTextBoxColumn qty = new DataGridViewTextBoxColumn();
            qty.DataPropertyName = detailTbl.qtyColumn.ColumnName;
            qty.HeaderText = "Lượng";
            qty.Name = ColumnNames.qty.ToString();
            qty.DefaultCellStyle = qtyCellType;
            qty.Width = 80;

            // 
            // whQty
            // 
            DataGridViewTextBoxColumn whQty = new DataGridViewTextBoxColumn();
            whQty.DataPropertyName = detailTbl.whQtyColumn.ColumnName;
            whQty.HeaderText = "Lượng tồn";
            whQty.Name = ColumnNames.whQty.ToString();
            whQty.DefaultCellStyle = whQtyCellType;
            whQty.Width = 80;
            whQty.Visible = false;
            whQty.ReadOnly = true;
          
            // 
            // convertUnit
            // 
            DataGridViewComboBoxColumn convertUnit = new DataGridViewComboBoxColumn();
            convertUnit.DataSource = itemSource;
            convertUnit.DataPropertyName = detailTbl.itemCodeColumn.ColumnName;
            convertUnit.DisplayMember = "convertUnit";
            convertUnit.HeaderText = "ĐVT";
            convertUnit.Name = ColumnNames.convertUnit.ToString();
            convertUnit.ReadOnly = true;
            convertUnit.ValueMember = "itemCode";
            convertUnit.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
            convertUnit.DefaultCellStyle.BackColor = CommonTypes.Settings.sysColorDisableBG;
            convertUnit.DefaultCellStyle.ForeColor = CommonTypes.Settings.sysColorDisableFG;
            convertUnit.Width = 40;

            // 
            // convertQty
            // 
            DataGridViewTextBoxColumn convertQty = new DataGridViewTextBoxColumn();
            convertQty.HeaderText = "SL.quy.đổi";
            convertQty.DataPropertyName = detailTbl.convertQtyColumn.ColumnName;
            convertQty.Name = ColumnNames.convertQty.ToString();
            convertQty.Width = 80;
            convertQty.DefaultCellStyle = qtyCellType;
            convertQty.Visible = false;
            // 
            // convertMetric
            //
            DataGridViewTextBoxColumn convertMetric = new DataGridViewTextBoxColumn();
            convertMetric.HeaderText = "Hệ.số.đổi";
            convertMetric.DataPropertyName = detailTbl.convertMetricColumn.ColumnName;
            convertMetric.Name = ColumnNames.convertMetric.ToString();
            convertMetric.DefaultCellStyle = qtyCellType;
            convertMetric.Width = 70;
            convertMetric.Visible = false;

            // 
            // deliveryLot
            // 
            common.controls.DataGridViewTextBoxColumnExt deliveryLot = new common.controls.DataGridViewTextBoxColumnExt();
            deliveryLot.DataPropertyName = detailTbl.deliveryLotColumn.ColumnName;
            deliveryLot.HeaderText = "Đợt";
            deliveryLot.Name = ColumnNames.deliveryLot.ToString();
            deliveryLot.Width = 35;
            deliveryLot.Uppercase = true;
            deliveryLot.Visible = false;

            // 
            // Notes
            // 
            DataGridViewTextBoxColumn notes = new DataGridViewTextBoxColumn();
            notes.DataPropertyName = detailTbl.notesColumn.ColumnName;
            notes.HeaderText = "  Ghi chú";
            notes.Name = ColumnNames.notes.ToString();
            notes.Width = 130;

            // 
            // contractNo
            // 
            common.controls.DataGridViewTextBoxColumnExt contractNo = new common.controls.DataGridViewTextBoxColumnExt();
            contractNo.DataPropertyName = detailTbl.contractNoColumn.ColumnName;
            contractNo.HeaderText = "Hợp đồng";
            contractNo.Name = ColumnNames.contractNo.ToString();
            contractNo.Width = 120;
            contractNo.Uppercase = true;
            contractNo.Visible = false; 

            // 
            // HouseCode
            // 
            BindingSource houseSource = new BindingSource();
            data.masterDS.wareHouseDataTable tbl = application.SysLibs.LoadWareHouse(CommonTypes.Settings.sysLoginInfo.UserId);
            houseSource.DataSource = tbl;

            BindingSource refHouseSource = new BindingSource();
            refHouseSource.DataSource = tbl;

            DataGridViewComboBoxColumn houseCode = new DataGridViewComboBoxColumn();
            houseCode.Name = ColumnNames.houseCode.ToString();
            houseCode.HeaderText = "Mã.kho";
            houseCode.DataPropertyName = detailTbl.houseCodeColumn.ColumnName;
            houseCode.DataSource = houseSource;
            houseCode.DisplayMember = DataAccess.DataCache.myMasterDS.wareHouse.houseCodeColumn.ColumnName;
            houseCode.ValueMember = DataAccess.DataCache.myMasterDS.wareHouse.houseCodeColumn.ColumnName;
            houseCode.Width = 120;
            houseCode.Visible = false;

            // 
            // actionBtn
            // 
            common.controls.gridViewImageColumn actionBtn = new common.controls.gridViewImageColumn();
            actionBtn.Name = ColumnNames.actionBtn.ToString();
            actionBtn.myImageType = common.controls.imageType.Edit;
            actionBtn.HeaderText = "";
            actionBtn.Width = 25;
            actionBtn.Visible = false;

            // 
            // myDetailGrid
            // 
            this.Visible = true;
            this.DataSource = dataSource;

            this.ReadOnly = false;
            this.ScrollBars = ScrollBars.Vertical;
            this.AutoGenerateColumns = false;
            this.Columns.Clear();
            this.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
                    checkOut,itemCode,subCode,techCode,itemName,unit,qty,convertMetric,
                    convertQty,convertUnit,whQty,contractNo,houseCode,deliveryLot,notes,actionBtn});
            this.myAutoFitColumn = ColumnNames.itemName.ToString();
            this.DisbaleReadOnlyColumns();

        }
        protected override void OnDefaultValuesNeeded(DataGridViewRowEventArgs e)
        {
            base.OnDefaultValuesNeeded(e);
            if (e == null) return;
            string saveHouseCode = "" , saveDeliveryLot = "";
            if (this.CurrentRow != null)
            {
                saveHouseCode = this.CurrentRow.Cells[ColumnNames.houseCode.ToString()].Value.ToString();
                saveDeliveryLot = this.CurrentRow.Cells[ColumnNames.deliveryLot.ToString()].Value.ToString();
            }
            if (myDataSource.Current != null)
                DataAccess.DataLibs.InitData((data.applicationDS.InventoryDetailRow)((DataRowView)myDataSource.Current).Row);

            if (this.Columns[ColumnNames.deliveryLot.ToString()].Visible)
                e.Row.Cells[ColumnNames.deliveryLot.ToString()].Value = saveDeliveryLot;

            if (this.Columns[ColumnNames.houseCode.ToString()].Visible)
                e.Row.Cells[ColumnNames.houseCode.ToString()].Value = saveHouseCode;

        }
        public override void Refresh()
        {
            if (IsOnProcessing) return;
            try
            {
                IsOnProcessing = true;
                UpdateItemList(null);
                IsOnProcessing = false;
                base.Refresh();
            }
            catch (Exception er)
            {
                IsOnProcessing = false;
                ErrorHandler(this, er);
            }
        }

        public override bool CheckData()
        {
            this.myDataSource.EndEdit();
            return DoValidateData(OnRowValidate);
        }
        private void OnRowValidate(DataGridViewRow row, common.controls.GridRowValidateEventArgs e)
        {
            if (row.DataBoundItem == null) return;

            if (this.Columns[ColumnNames.itemCode.ToString()].Visible)
            {
                if (row.Cells[ColumnNames.itemCode.ToString()].Value.ToString().Trim() == "")
                {
                    e.ErrorText.Add(String.Format("Dữ liệu [{0}] trống", this.Columns[ColumnNames.itemCode.ToString()].HeaderText));
                    e.HaveError = true;
                }
            }
            //=========================
            //Check data contrainsts
            //=========================

            if (this.Columns[ColumnNames.itemCode.ToString()].Visible &&
                row.Cells[ColumnNames.itemCode.ToString()].Value.ToString().Trim() != "" &&
                DataAccess.DataCache.FindITEM(row.Cells[ColumnNames.itemCode.ToString()].Value.ToString()) == null)
            {
                e.ErrorText.Add(String.Format("Dữ liệu [{0}] không hợp lệ", this.Columns[ColumnNames.itemCode.ToString()].HeaderText));
                e.HaveError = true;
            }
            if (this.Columns[ColumnNames.houseCode.ToString()].Visible &&
                row.Cells[ColumnNames.houseCode.ToString()].Value.ToString().Trim() != "" &&
                DataAccess.DataCache.FindWAREHOUSE(row.Cells[ColumnNames.houseCode.ToString()].Value.ToString()) == null)
            {
                e.ErrorText.Add(String.Format("Dữ liệu [{0}] không hợp lệ", this.Columns[ColumnNames.houseCode.ToString()].HeaderText));
                e.HaveError = true;
            }
            if (this.Columns[ColumnNames.contractNo.ToString()].Visible &&
                            row.Cells[ColumnNames.contractNo.ToString()].Value.ToString().Trim() != "" &&
                            DataAccess.DataCache.FindCONTRACT(row.Cells[ColumnNames.contractNo.ToString()].Value.ToString()) == null)
            {
                e.ErrorText.Add(String.Format("Dữ liệu [{0}] không hợp lệ", this.Columns[ColumnNames.contractNo.ToString()].HeaderText));
                e.HaveError = true;
            }
        }
        
        //Add import from PDA
        protected override void CreateContextMenu()
        {
            base.CreateContextMenu();
            AddContextMenu(myMenuName.rItem1, "Nhập từ tệp PDA", importDromPDA_Click);
        }
        protected override void WhenContextMenuStripOpening(object sender, CancelEventArgs e)
        {
            base.WhenContextMenuStripOpening(sender, e);
            ContextMenuEnable(myMenuName.rItem1, !this.isLockEdit);
        }
        private void ValueChanged(object sender, common.controls.GridEventArgs e)
        {
            if (this.CurrentCell == null || !this.IsValidCell(e.RowIndex, e.ColumnIndex)) return;

            if (this.Columns[e.ColumnIndex].Name == ColumnNames.itemCode.ToString())
            {
                string itemCode = this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                if (common.StringLibs.IsNullOrEmpty(itemCode) == false)
                {
                    bool HaveMarker = common.SysLibs.HaveFindMarker(ref itemCode);
                    if (HaveMarker == false)
                    {
                        string code = application.AppLibs.GetItemCodeFromCodeId(itemCode);
                        if (code != null)
                        {
                            itemCode = code;
                            this.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = itemCode;
                        }
                    }
                    data.masterDS.ItemRow itemRow = DataAccess.DataCache.FindITEM(itemCode);
                    if (itemRow == null) FindData(this, new common.controls.GridEventArgs(e.RowIndex, e.ColumnIndex));
                }
            }
            if ((this.Columns[e.ColumnIndex].Name == ColumnNames.qty.ToString()) ||
                (this.Columns[e.ColumnIndex].Name == ColumnNames.convertQty.ToString()) ||
                (this.Columns[e.ColumnIndex].Name == ColumnNames.convertMetric.ToString()))
            {
                decimal d1 = 0, d2 = 0;
                decimal.TryParse(this.CurrentRow.Cells[ColumnNames.qty.ToString()].Value.ToString(), out d1);
                decimal.TryParse(this.CurrentRow.Cells[ColumnNames.convertMetric.ToString()].Value.ToString(), out d2);
                if (d1 * d2 != 0)
                    this.CurrentRow.Cells[ColumnNames.convertQty.ToString()].Value = (d1 * d2);
                else this.CurrentRow.Cells[ColumnNames.convertQty.ToString()].Value = DBNull.Value;
            }
        }

        private void FindData(object sender, common.controls.GridEventArgs arg)
        {
            string findCode = this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].EditedFormattedValue.ToString(); ;
            if (this.CurrentCell == null) return;
            //Code
            if (this.Columns[arg.ColumnIndex].Name.Trim() == ColumnNames.itemCode.ToString())
            {
                application.dataFind.myItemFind.Find(findCode, true);
                data.masterDS.ItemRow itemRow = application.dataFind.myItemFind.selectedDataRow;
                if (itemRow != null)
                {
                    this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = itemRow.itemCode;
                    UpdateItemList(itemRow.itemCode);
                }
                else this.Rows[arg.RowIndex].Cells[arg.ColumnIndex].Value = DBNull.Value;
                this.myDataSource.ResetCurrentItem();
                this.myDataSource.EndEdit(); 
            }
            //ContractNo
            if (this.Columns[arg.ColumnIndex].Name.Trim() == ColumnNames.contractNo.ToString())
            {
                string contractNo = this.CurrentCell.EditedFormattedValue.ToString();
                application.dataFind.myContractFind.Find(contractNo,true);
                data.applicationDS.ContractRow contractRow = application.dataFind.myContractFind.selectedDataRow;
                if (contractRow != null)
                {
                    this.CurrentRow.Cells[arg.ColumnIndex].Value = contractRow.contractNo;
                    this.myDataSource.ResetCurrentItem();
                    this.myDataSource.EndEdit(); 
                }
                this.Focus();
            }
        }

        private OpenFileDialog openFileDialog = null;
        private void importDromPDA_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.isLockEdit) return;
                if (openFileDialog == null)
                {
                    openFileDialog = new OpenFileDialog();
                    common.DialogLibs.SetFileDialogTEXT(openFileDialog);
                }
                openFileDialog.ShowDialog();
                if (openFileDialog.FileName==null) return;
                
                char[] sepas = new char[] { ',' };
                if (!common.fileFuncs.FileExist(openFileDialog.FileName)) return;
                System.IO.StreamReader file = System.IO.File.OpenText(openFileDialog.FileName);

                data.applicationDS.InventoryDetailRow detailRow;

                //Delete empty row
                string itemColumnName = ColumnNames.itemCode.ToString();
                this.myDataSource.EndEdit();
                foreach (DataGridViewRow row in this.Rows)
                {
                    if (row.IsNewRow) continue;
                    if (row.Cells[itemColumnName].Value==null ||
                        row.Cells[itemColumnName].Value.ToString().Trim()=="")
                    {
                        this.Rows.Remove(row);
                    }
                }

                while (!file.EndOfStream)
                {
                    string[] items = file.ReadLine().Split(sepas);
                    if (items.Length < 2) continue;
                    this.myDataSource.AddNew();
                    if (myDataSource.Current == null) continue;
                    detailRow =  (data.applicationDS.InventoryDetailRow)((DataRowView)myDataSource.Current).Row;
                    DataAccess.DataLibs.InitData(detailRow);
                    
                    //Barcode -> item code 
                    detailRow.itemCode = items[0];
                    string code = application.AppLibs.GetItemCodeFromCodeId(detailRow.itemCode);
                    if (code != null)  detailRow.itemCode  = code;

                    detailRow.qty = decimal.Parse(items[1]);
                }
                file.Close();
                this.Refresh();
            }
            catch (Exception er)
            {
                ErrorHandler(this, er);
            }
        }
    }
}
